<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { buildFileList } from '@/utils/fileUtils'
import { getAccessToken } from '@/utils/auth'
import * as UserApi from '@/api/system/user/index'
import * as DefinitionApi from '@/api/bpm/definition'
import { VehicleSafetyApi, VehicleSafetyVO } from '@/api/safety/vehicleMonitoring'
import { CarOwnerApi } from '@/api/safety/vehicleMonitoring/vehicleowner'
import { useMessage, useToast } from 'wot-design-uni'

const userList = ref<any[]>([]) // 用户列表
const carOwnerList = ref<any[]>([]) // 车主列表
const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const auditForm = ref() // 表单 Ref
const detailId = ref(null)
const resubmit = ref(0)

// 指定审批人
const processDefineKey = 'safety_vehicleMonitoring' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRef = ref() // 发起人选择审批人的表单 Ref
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules
const formData = ref<VehicleSafetyVO>({} as any)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
// 独立文件存储（按字段名存储）
const fileLists = ref<Record<string, any[]>>({
	attachments: []
})

const handlelicensePlateChange = ({ value }: { value: any }) => {
	const selected = carOwnerList.value.find(item => item.carNo === value)
	formData.value.ownerName = selected.ownerName
	formData.value.ownerPthone = selected.phone
}

const formFields = ref<any[]>([

	// { type: 'input', prop: 'ownerShip', label: '线路', placeholder: '请输入线路' },
	{
		type: 'radio',
		prop: 'gpsIsGood',
		label: 'GPS是否完好',
		width: 150,
		rules: [
			{ required: true, message: 'GPS是否完好', trigger: 'change' }
		],
		options: [
			{ label: '是', value: '1' },
			{ label: '否', value: '0' }
		],
		optionLabel: 'label',
		optionValue: 'value',
		inline: true,
	},
	{
		type: 'select', prop: 'licensePlate', label: '车牌号', placeholder: '请选择车牌号',
		filterable: true,
		clearable: true,
		options: () => carOwnerList.value,
		valueKey: 'carNo',
		labelKey: 'carNo',
		onChange: handlelicensePlateChange
	},
	{ type: 'input', prop: 'ownerName', label: '车主姓名', placeholder: '请输入车主', readonly: true },

	{ type: 'input', prop: 'ownerPthone', label: '车主电话', placeholder: '请输入车主电话', readonly: true },

	{ type: 'input', prop: 'monitorName', label: '监控员姓名', placeholder: '请输入监控员姓名', },
	{
		type: 'datetime',
		prop: 'startTime',
		label: '发起时间',
		placeholder: '请选择发起时间',
		// datetimeType: 'date',
	},
	// {
	// 	type: 'select',
	// 	prop: 'inspectorName',
	// 	label: '安全检测人',
	// 	placeholder: '请选择安全检测人',
	// 	options: () => userList.value,
	// 	valueKey: 'id',
	// 	labelKey: 'nickname',
	// 	selectType: 'radio', // 自定义字段，表示用 radio 类型的 wd-select-picker
	// 	filterable: true,
	// 	clearable: true
	// },
	// { type: 'input', prop: 'inspectorPhone', label: '安全检测人电话', placeholder: '请输入安全检测人电话' },
	// {
	// 	type: 'select',
	// 	prop: 'vehicleMonitor',
	// 	label: '车辆监控确认人员',
	// 	placeholder: '请选择安全检测人',
	// 	options: () => userList.value,
	// 	valueKey: 'id',
	// 	labelKey: 'nickname',
	// 	selectType: 'radio',
	// 	filterable: true,
	// 	clearable: true
	// },
	// {
	// 	type: 'upload', prop: 'attachments', label: '附件',
	// 	action: globalConfig.uploadUrl,
	// 	accept: 'all',
	// 	limit: 1,
	// 	imageMode: 'aspectFill',
	// 	header: headerObj.value,
	// 	targetMapping: {         // 字段映射配置
	// 		fileUrl: 'attachments',    // 接口返回ID -> formData.serverIds
	// 		fileName: 'ename'     // 文件名 -> formData.fileName
	// 	}
	// },
	{ type: 'input', prop: 'remark', label: '备注', placeholder: '请输入备注' }
])
const formRules = reactive<any>({
	licensePlate: [
		{
			required: true,
			message: '车牌号不能为空',
			trigger: ['blur', 'change'],
		},
		// {
		// 	pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-HJ-NP-Z][A-HJ-NP-Z0-9]{4,5}[A-HJ-NP-Z0-9挂学警港澳]$/,
		// 	message: '车牌号格式不正确',
		// 	trigger: ['blur', 'change'],

		// }
	],
	ownerShip: [
		{
			required: true,
			message: '线路不能为空',
			trigger: ['blur', 'change'],
		},
	],
	ownerName: [
		{
			required: true,
			message: '车主姓名不能为空',
			trigger: ['blur', 'change'],
		},
	],
	ownerPthone: [
		{
			required: true,
			message: '车主电话不能为空',
			trigger: ['blur', 'change'],
		},
		// {
		// 	pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
		// 	,
		// 	message: '请输入有效的电话号',
		// 	trigger: ['blur', 'change'],
		// }
	],
	gpsIsGood: [
		{
			required: true,
			message: 'GPS是否完好不能为空',
			trigger: ['blur', 'change'],
		},
	],
	monitorName: [
		{
			required: true,
			message: '监控员姓名不能为空',
			trigger: ['blur', 'change'],
		},
	],
	startTime: [
		{
			required: true,
			message: '请选择发起时间',
			trigger: ['blur', 'change'],
		},
	],
	// inspectorName: [{ required: true, message: '安全检测人不能为空', trigger: ['blur', 'change'], }],
	// inspectorPhone: [
	// 	{ required: true, message: '安全检测人电话不能为空', trigger: ['blur', 'change'], },
	// 	{
	// 		pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
	// 		,
	// 		message: '请输入有效的电话号',
	// 		trigger: ['blur', 'change'],
	// 	}
	// ],
	// vehicleMonitor: [
	// 	{ required: true, message: '车辆监控确认人员不能为空', trigger: ['blur', 'change'], },

	// ],
})



onLoad(async (options) => {
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	await gecarOwnerList()
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
	// 加载用户列表
	getUserList()

})

/** 获取用户列表 */
const getUserList = async () => {
	try {
		userList.value = await UserApi.getSimpleUserList();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		userList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
/** 获取车主列表 */
const gecarOwnerList = async () => {
	try {
		carOwnerList.value = await CarOwnerApi.listAllSimpleCarOwner();
	} catch (error) {
		console.error("获取用户列表失败:", error);
		carOwnerList.value = []; // 失败时，防止 userOptions.value 变成 undefined
	}
}
/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await VehicleSafetyApi.getVehicleSafety(Number(detailId.value))
		formData.value = data
		// 附件字段回显
		fileLists.value.attachments = buildFileList(data.attachments);
	} catch (error) {
		console.log('加载数据失败')
	}
}

/** 提交表单 */
const submitForm = async (payload: any) => {
	const { type, data } = payload
	try {
		if (type === 'update') {
			await VehicleSafetyApi.updateVehicleSafety(data)
			toast.success('编辑成功');
		} else {
			await VehicleSafetyApi.createVehicleSafety(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/safety/vehicleMonitoring/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}
/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/safety/vehicleMonitoring/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>